Lesson 4: Introduction to Java Swing
Objective:
In this lesson, you'll understand the basics of Java Swing and how it integrates with Java programming to create graphical user interfaces (GUIs). You'll set up a simple window, add components, and learn how Swing fits within Java's ecosystem.
What is Java Swing?
Java Swing is a part of Java's Standard Library, offering a rich set of GUI components to build applications that can interact with the user visually. Swing is built on top of AWT (Abstract Window Toolkit), but unlike AWT, Swing provides a more flexible and feature-rich platform for creating graphical interfaces.
Setting Up the Environment
Before you can start coding with Swing, you need to make sure that your development environment is ready:
- Download and Install JDK (Java Development Kit):
- If you haven't already, download the latest version of the JDK from Oracle's official website.
- IDE Setup:
You can use any IDE, but I recommend using Eclipse, NetBeans, or IntelliJ IDEA for their built-in support for Swing development.
Code Example: Simple JFrame with JLabel
Let’s start by creating a basic window using JFrame
and a simple JLabel
.
import javax.swing.JFrame;
import javax.swing.JLabel;
public class HelloSwing {
public static void main(String[] args) {
// Create a JFrame (Main window)
JFrame frame = new JFrame("Hello Java Swing");
// Create a JLabel (Text component)
JLabel label = new JLabel("Welcome to Java Swing!");
// Add the label to the frame
frame.add(label);
// Set frame properties
frame.setSize(400, 200); // Set the size of the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the app when the window is closed
frame.setVisible(true); // Make the window visible
}
}
Code Explanation:
- JFrame: This is the main window of your application. It acts as the container for all other components.
- JLabel: A simple text component that is displayed on the window.
- frame.add(label): Adds the label to the frame.
- frame.setSize(400, 200): Sets the size of the window (width: 400px, height: 200px).
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Ensures that the application closes when the user closes the window.
- frame.setVisible(true): Makes the window visible on the screen.